import { supabase } from "./supabaseClient";
import db from '../utils/db';

const orderMap = {
    '一': 1,
    '二': 2,
    '三': 3,
    '四': 4,
    '五': 5,
    '六': 6,
    '七': 7,
    '八': 8,
    '九': 9,
    '十': 10
  };

const getNumber = (str) => {
    if (!str || !str.startsWith('第')) return null;
    const match = str.match(/^第([一二三四五六七八九十]+)/);
    return match ? match[1] : null;
};

export const textbookService = {
     getChapters : async () => {
        try {
            const dataa = await db.getAll('textbooks');
            if(dataa && dataa.length > 0) {
                dataa.sort((a, b) => {
                    const numA = getNumber(a.chapter_title);
                    const numB = getNumber(b.chapter_title);
                    const orderA = numA && orderMap[numA] ? orderMap[numA] : Infinity;
                    const orderB = numB && orderMap[numB] ? orderMap[numB] : Infinity;
                    return orderA - orderB;
                });
                dataa.sort((a, b) => a.book_title.localeCompare(b.book_title));
                return dataa;
            }
            const { data, error } = await supabase
                .rpc('get_textbook_chapters');
            if (error) {
                throw error;
            }
            const transaction = db.transaction('textbooks', 'readwrite');
            const store = transaction.objectStore('textbooks');
            data.forEach(item => {
                store.put(item);
            });
            return data;
        } catch (error) {
            console.error('Error fetching textbooks:', error);
            return null;
        }
    },
    // 获取以book_title为键的章节列表
    getChaptersByBook : async () => {
        try {
            const chapterList = await textbookService.getChapters();
            if(chapterList && chapterList.length > 0) {
                return chapterList.reduce((acc, chapter) => {
                    const { book_title, chapter_title } = chapter;
                    if (!acc[book_title]) {
                        acc[book_title] = [];
                    }
                    acc[book_title].push(chapter_title);
                    return acc;
                }, {});
            }
        } catch (error) {
            console.error('Error fetching textbooks:', error);
        }
        return {};
    },
}
